package com.yuedou.jylt.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate.entity.UpdateEntity;
import com.xuexiang.xupdate.proxy.IUpdateProxy;
import com.xuexiang.xupdate.proxy.impl.DefaultUpdateChecker;
import com.youth.banner.config.IndicatorConfig;
import com.youth.banner.indicator.CircleIndicator;
import com.yuedou.jylt.MainActivity;
import com.yuedou.jylt.R;
import com.yuedou.jylt.adapter.ChangeBanner;
import com.yuedou.jylt.adapter.MediaVideoBannerAdapter;
import com.yuedou.jylt.bean.ResourceBean;
import com.yuedou.jylt.constant.Const;
import com.yuedou.jylt.constant.MApplication;
import com.yuedou.jylt.dto.ResponseObj;
import com.yuedou.jylt.dto.param.InitDeviceParam;
import com.yuedou.jylt.http.RequestServices;
import com.yuedou.jylt.http.RequestUtils;
import com.yuedou.jylt.manager.BannerVideoManager;
import com.yuedou.jylt.sharedpref.SharedPrefConstant;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PlayVideoActivity extends Activity {

    @BindView(R.id.banner_video)
    ChangeBanner banner;
    @BindView(R.id.img_qrcode)
    ImageView img_qrcode;


    @BindView(R.id.btn_test)
    Button btn_test;

    @BindView(R.id.txtAppVersion)
    TextView txtAppVersion;
    @BindView(R.id.txtDeviceSn)
    TextView txtDeviceSn;
    @BindView(R.id.txtDeviceState)
    TextView txtDeviceState;
    @BindView(R.id.txtNetwork)
    TextView txtNetwork;

    private List<ResourceBean> dataList = new ArrayList<>();
    private MediaVideoBannerAdapter mAdapter;
    private BannerVideoManager mBannerVideoManager;

    public static final String TAG = "PlayVideoActivity";
    private Unbinder unbinder;
    private Context context;
    String version;

    private MediaPlayer mediaPlayer = null;
    private static final long SPLASH_DELAY_MILLIS = 10;
    private static final int GO_HOME = 1000;
    private static final int ON_LINE = 1001;
    private static final int OFF_LINE = 1002;
    private static final int NET_FOUR_G = 1003;
    private static final int NET_WIFI = 1004;
    private static final int PLAY_VIDEO = 1005;
    private ConnectivityManager connectivityManager;
    private String simSeriaNumber = "";
    private GestureDetector gestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_video);
        context = PlayVideoActivity.this;
        unbinder = ButterKnife.bind(this);
//        EventBus.getDefault().register(this);

        this.version = MApplication.mSharedPref.getSharePrefString(SharedPrefConstant.DEVICE_MATERIAL_VERSION);

        //屏幕双击事件
//        gestureDetector = new GestureDetector(context, new MySimpleGesture() {
//            @Override
//            public boolean onDoubleTap(MotionEvent e) {
//                //双击
////                clickEvent(e, true);
//                Log.i("","ssssss");
//                Intent intent = new Intent(context, SettingActivity.class);
//                startActivity(intent);
//                return super.onDoubleTap(e);
//            }
//        });
//        gestureDetector.setIsLongpressEnabled(true);

        initLocalFileList();
        mAdapter = new MediaVideoBannerAdapter(this, dataList);
        banner.isAutoLoop(true);
        banner.setAdapter(mAdapter).
                setIndicator(new CircleIndicator(this))
                .setIndicatorGravity(IndicatorConfig.Direction.CENTER);
        mBannerVideoManager = new BannerVideoManager(this, banner, mAdapter, dataList);
        mBannerVideoManager.setPageChangeMillis(10000);
        mBannerVideoManager.setVideoPlayLoadWait(10000);
        connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);

        String deviceSn = MApplication.mSharedPref.getSharePrefString(SharedPrefConstant.DEVICE_SN);
        if(!TextUtils.isEmpty(deviceSn)){
            txtDeviceSn.setText("设备编号："+deviceSn);
        }

        //获取系统的TelephonyManager对象
        TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        //获取sim卡序列号
        if(tManager!=null){
//            this.simSeriaNumber = tManager.getSimSerialNumber();
            System.out.println("SIM 卡编号：" + simSeriaNumber);
        }


        try {
            String appVerisonName = getVersionName();
            txtAppVersion.setText("版本号：V "+appVerisonName);
        } catch (Exception e) {
            e.printStackTrace();
        }

        int deviceState = MApplication.mSharedPref.getSharePrefInteger(SharedPrefConstant.DEVICE_ONLINE_STATE);
        if(deviceState == 1){
            txtDeviceState.setText("设备状态：在线");
        }else{
            txtDeviceState.setText("设备状态：离线");
//            onHttpDeviceDetail(Build.SERIAL);
        }

        txtNetwork.setText("网络：未连接");
        NetworkInfo.State grasState = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
        if(grasState != null){
            if(grasState.toString().equals("CONNECTED")){
                txtNetwork.setText("网络：" + "4G");
            }
        }
        NetworkInfo.State wifiState = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        if(wifiState!=null){
            if(wifiState.toString().equals("CONNECTED")){
                txtNetwork.setText("网络：" + "WIFI");
            }
        }

        if (ContextCompat.checkSelfPermission(PlayVideoActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(PlayVideoActivity.this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE }, 1);
        } else {
//            initMediaPlayer();//初始化MediaPlayer
        }


        String qrCode = MApplication.mSharedPref.getSharePrefString(SharedPrefConstant.DEVICE_QRCODE);
        System.out.println("qrCode:" + qrCode);
        if(!TextUtils.isEmpty(qrCode)){
            Picasso.with(context).load(qrCode).into(img_qrcode);
        }

        new Thread(new MyThreadPlay()).start();

        updateApp();
    }

    public class MyThreadPlay implements Runnable {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {
                Thread.sleep(10000);// 线程暂停10秒，单位毫秒
                Message message = new Message();
                message.what = 1;
                message.obj = Build.SERIAL;
                mHandler.sendEmptyMessageDelayed(GO_HOME, SPLASH_DELAY_MILLIS);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


    @OnClick({R.id.btn_test,R.id.img_qrcode})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_test:
                // 系统通知
                mediaPlayer.setVolume(1f, 1f);;//开始播放开箱成功
                mediaPlayer.start();//开始播放开箱成功
                break;
            case R.id.img_qrcode:
                Intent intent = new Intent(context, MainActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     *  获取设备详情的 网络请求
     */
    private void onHttpDeviceDetail(String serialNumber){
        System.out.println("onHttpDeviceDetail==================");
        //步骤4:创建Retrofit对象
        RequestServices requestServices = RequestUtils.getRetrofit().create(RequestServices.class);
        //对 发送请求 进行封装
        InitDeviceParam deviceParam = new InitDeviceParam();
        deviceParam.setCpu_id(serialNumber);
        deviceParam.setSim_card_num(this.simSeriaNumber);
        System.out.println("deviceParam: " +  deviceParam.toString());
        Call<ResponseObj> call = requestServices.robotDetail(deviceParam);
        //步骤6:发送网络请求(异步)
        call.enqueue(new Callback<ResponseObj>() {
            @Override
            public void onResponse(Call<ResponseObj> call, @NonNull Response<ResponseObj> response) {
                Log.i("获取初始化设备 返回数据",response.toString());
                ResponseObj responseObj = response.body();
                System.out.println("获取初始化设备 返回数据: " + response.body().toString());
                System.out.println("data: " + responseObj.getData().toString());
                System.out.println();
                if (responseObj != null) {
                    // 成功
                    int deviceId = responseObj.getData().containsKey("id")
                            ? Integer.parseInt(responseObj.getData().get("id").toString()) : 0;
                    String qrCode = responseObj.getData().get("qrCode").toString();
                    String deviceSn = responseObj.getData().get("serialNum").toString();
                    int state = responseObj.getData().containsKey("state")
                            ? Integer.parseInt(responseObj.getData().get("state").toString()) : 0;
//                    String version = responseObj.getData().get("version").toString();


                    MApplication.mSharedPref.putSharePrefInteger(SharedPrefConstant.DEVICE_ID,deviceId);
                    MApplication.mSharedPref.putSharePrefString(SharedPrefConstant.DEVICE_SN,deviceSn);

                    MApplication.mSharedPref.putSharePrefString(SharedPrefConstant.DEVICE_QRCODE,qrCode);
                    MApplication.mSharedPref.putSharePrefInteger(SharedPrefConstant.DEVICE_STATE,state);
//                    MApplication.mSharedPref.putSharePrefString(SharedPrefConstant.DEVICE_MATERIAL_VERSION,version);

                    //创建缓存目录，系统一运行就得创建缓存目录的，
                    String destDir = Environment.getExternalStorageDirectory().toString() + "/material";
                    System.out.println("destDir : " + destDir);
                    File cache = new File(Environment.getExternalStorageDirectory().toString(), "material");
                    if(!cache.exists()){
                        boolean blMk = cache.mkdirs();
                        if(blMk){
                            System.out.println("创建成功");
                        }else{
                            System.out.println("创建失败");
                        }
                    }

                }
            }

            @Override
            public void onFailure(Call<ResponseObj> call, Throwable t) {
                t.printStackTrace();
                Log.d("获取设备信息详情 失败", t.getMessage());
            }
        });
    }

    /**
     * 播放音频文件
     */
    private void initMediaPlayer(){
        try {
            mediaPlayer = new MediaPlayer();
            AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.open_video);
            mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    System.out.println("播放========");
                    if(mediaPlayer.isPlaying()){
                        System.out.println("播放停止========");
//                        mediaPlayer.stop();//开始播放开箱成功
                        stopPlay();
                    }
                }
            });

            //设置出错的监听器
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    //提示用户
                    stopPlay();
                    //释放播放器
                    return true;
                }
            });
//            mediaPlayer.setDataSource(file.getPath());//指定音频文件的路径
            mediaPlayer.prepare();//让MediaPlayer进入到准备状态
            mediaPlayer.setVolume(1f, 1f);;//开始播放开箱成功
            mediaPlayer.setLooping(false);
            mediaPlayer.start();//开始播放开箱成功
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止播放
     */
    public void stopPlay() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.stop();
            } catch (Exception e) {
                e.printStackTrace();
                mediaPlayer = null;
                mediaPlayer = new MediaPlayer();
                mediaPlayer.stop();
            }

            mediaPlayer.release();
            mediaPlayer = null;
        }
    }


    /**
     * Handler:跳转到不同界面
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GO_HOME:
                    int deviceState = MApplication.mSharedPref.getSharePrefInteger(SharedPrefConstant.DEVICE_ONLINE_STATE);
                    if(deviceState == 0){
//                        onHttpDeviceDetail(Build.SERIAL);
                    }
                    break;
                case ON_LINE:
                    txtDeviceState.setText("设备状态：在线");
                    break;
                case OFF_LINE:
                    txtDeviceState.setText("设备状态：离线");
//            String deviceSn = MApplication.mSharedPref.getSharePrefString(SharedPrefConstant.DEVICE_SN);
//                    onHttpDeviceDetail(Build.SERIAL);
                    break;
                case NET_FOUR_G:
                    txtNetwork.setText("网络：" + "4G");
                    break;
                case NET_WIFI:
                    txtNetwork.setText("网络：" + "WIFI");
                    break;
                case PLAY_VIDEO:
                    System.out.println("播放音频===");
                    initMediaPlayer();
                    try {
                        Thread.sleep(4000);
                        stopPlay();
                    } catch (InterruptedException e) {
                        System.out.println("========InterruptedException: =========" + e.getMessage());
                        e.printStackTrace();
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    /**
     *  获取当前APP版本号
     * @return
     * @throws Exception
     */
    private String getVersionName() throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0);
        String version = packInfo.versionName;
        return version;
    }

    /**
     *  app更新
     */
    public void updateApp(){
        XUpdate.newBuild(context)
                .updateUrl(Const.APP_VERSION_URL)
                .updateChecker(new DefaultUpdateChecker() {
                    @Override
                    public void onBeforeCheck() {
                        super.onBeforeCheck();
                    }

                    @Override
                    public void onAfterCheck() {
                        super.onAfterCheck();
                    }

                    @Override
                    public void processCheckResult(@NonNull String result, @NonNull IUpdateProxy updateProxy) {
                        super.processCheckResult(result, updateProxy);
                        try {
                            UpdateEntity updateEntity = updateProxy.parseJson(result);
                            if (updateEntity.isHasUpdate()) {
                                Log.d("TAG", "processCheckResult: 111");
                            } else {
                                Log.d("TAG", "processCheckResult: 222");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .update();
    }

    /**
     *  重新获取 当前轮播图片
     */
    private void initLocalFileList(){
        dataList = new ArrayList<>();
        this.version = MApplication.mSharedPref.getSharePrefString(SharedPrefConstant.DEVICE_MATERIAL_VERSION);
        System.out.println("广告版本号：" + this.version);
        String directory = Environment.getExternalStorageDirectory().toString() + "/material/" + this.version;
        List<String> imgs = getFilesAllName(directory);
        if(imgs != null && imgs.size() > 0){
            System.out.println("imgs: " + imgs.toString());
            for (String img : imgs){
                ResourceBean resourceBean = new ResourceBean();
                resourceBean.setType(1);
                resourceBean.setUrl("file://"+ img);
                dataList.add(resourceBean);
            }
            if(mBannerVideoManager!=null){
                mBannerVideoManager.resetList(dataList);
            }
        }else{

        }
    }


    public static List<String> getFilesAllName(String path) {
        File file = new File(path);
        File[] files = file.listFiles();
        if (files == null){
            Log.e("error","空目录");
            return null;
        }
        List<String> s = new ArrayList<>();
        for(int i = 0;i < files.length;i++){
            s.add(files[i].getAbsolutePath());
            System.out.println("");
        }
        return s;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mBannerVideoManager.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mBannerVideoManager.onPause();
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mBannerVideoManager.onDetachedFromWindow();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null){
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        unbinder.unbind();
    }

}